package com.longrise.android.byjk.plugins.vip.integralexchange;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.IntegralExchangeRefreshEvent;
import com.longrise.android.byjk.event.PersonalExchibitionEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by callxkj on 2017/4/28.
 * 积分兑换 1.3.6版本改为更换背景页面 并且只能从展业秀背景过来
 */

public class IntegralExchangeActivity extends BaseActivity implements
        SwipeRefreshLayout.OnRefreshListener, OnIntegralExchangeRcvItemClickListener {

    private static final String TAG = "IntegralExchangeActivity";

    private Toolbar mToolbar;
    private IExchangezyxbgAdapter mAdapter;
    private BBswipeRefreshLayout mBbsrl;
    private RecyclerView mRcv;
    private int mPosition;  //google跟踪使用

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_integralexchange;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        setTitle(AppUtil.getString(R.string.dailysign_ghbj));
        setSupportActionBar(mToolbar);
        mBbsrl = (BBswipeRefreshLayout) findViewById(R.id.integralexchange_srl);
        mRcv = (RecyclerView) findViewById(R.id.integralexchange_rcv);
        mBbsrl.setRefreshing(true);
        initRcv();
        initEvent();
        getData();
        EventBus.getDefault().register(this);
        addScreenName("展业秀更换背景");
    }

    private void initRcv() {
        View headView = View.inflate(mContext, R.layout.item_rcv_integralexchange_head, null);
        mAdapter = new IExchangezyxbgAdapter("更换背景");
        mAdapter.addHeaderView(headView);
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
        mRcv.setLayoutManager(layoutManager);
        mRcv.setAdapter(mAdapter);
    }

    private void initEvent() {
        mBbsrl.setOnRefreshListener(this);
        mAdapter.setOnRcvItemClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 获取展示的数据
     */
    private void getData() {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean fbean = new EntityBean();
        bean.set("scoretype", "100101");
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_vip_sCostRecordBygoodstype",
                fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int value = (Integer) bean.get("resultstate");
                            if (value == 1) {
                                EntityBean[] results = bean.getBeans("result");
                                parseResult(results);
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        refreshComplete();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }


    private void parseResult(EntityBean[] beans) {
        mAdapter.setDatas(beans, "100101"); //皮肤的type就是"100101"
    }

    @Override
    public void onRefresh() {
        getData();
    }

    private void refreshComplete() {
        mBbsrl.setRefreshing(false);
    }


    /**
     * @param type      1.点击汉字,2.点击图片
     * @param goodsid   商品id
     * @param goodstype 商品消费类型
     * @param imageUrl  大图片的地址
     * @param lockstate //解锁状态  1:已解锁  0：未解锁
     */
    @Override
    public void onClick(int type, String lockstate, String goodsid, String goodstype, String needscores, String imageUrl, String detailpicurl, int position) {
        this.mPosition = position;
        switch (type) {
            case 1:
                toTextClick(lockstate, goodsid, goodstype, needscores);
                break;
            case 2:
                toImageClick(imageUrl, lockstate, needscores, detailpicurl, goodsid, goodstype);
                break;
        }

    }

    /**
     * 点击的是文字
     */
    private void toTextClick(String lockstate, String goodsid, String goodstype, String needscores) {
        if ("1".equals(lockstate)) { //解锁状态  1:已解锁  0：未解锁不可能在更换背景页面  2:正在使用不能点击
            toChangeSkin(goodsid);
        }
    }

    /**
     * 点击的是图片
     */
    private void toImageClick(String imageUrl, String lockstate, String needscores,
                              String detailpicurl, String goodsid, String goodstype) {
        Bundle bundle = new Bundle();
        bundle.putString(IntegralExchangeImageActivity.IMAGEURL_INTENT, imageUrl);
        bundle.putString(IntegralExchangeImageActivity.LOCKSTATE_INTENT, lockstate);
        bundle.putString(IntegralExchangeImageActivity.NEEDSCORS_INTENT, needscores);
        bundle.putString(IntegralExchangeImageActivity.DETAILPICURL_INTENT, detailpicurl);
        bundle.putString(IntegralExchangeImageActivity.GOODSID_INTENT, goodsid);
        bundle.putString(IntegralExchangeImageActivity.GOODSTYPE_INTENT, goodstype);
        bundle.putInt(IntegralExchangeImageActivity.CURRENT_BACK_POSTION, mPosition);  //当前背景position
        bundle.putInt(IntegralExchangeImageActivity.PAGE_FROM_FLAG, IntegralExchangeImageActivity.PAGE_FROM_PERSONALEX);
        Intent intent = new Intent(this, IntegralExchangeImageActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

        //跟踪默认展业秀背景
        if (mPosition == 1) {
            addScreenName("默认展业秀背景");
        }

    }

    /**
     * 换肤
     */
    private void toChangeSkin(String goodsid) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("skinid", goodsid);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_uVIPstateBySkinid", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int value = (Integer) bean.get("resultstate");
                            if (value == 1) {
                                onRefresh();
                                EventBus.getDefault().post(new PersonalExchibitionEvent(PersonalExchibitionEvent.PECategory.GHPF));
                                finish();
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toRefresh(IntegralExchangeRefreshEvent bean) {
        if (bean.ismIsneedfinish()) {
            finish();
        } else {
            onRefresh();
        }

    }

    private void addScreenName(String name) {
        Tracker_Google.getInstance().addGoogleScreenName(name);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
